package com.csap.framework.validation;


import com.csap.framework.validation.annotation.Phone;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 手机号验证
 *
 * @Author ycf
 * @Date 2019-08-18 01:15
 */
public class PhoneValidator implements ConstraintValidator<Phone, String> {

    private boolean required = false;
    /**
     * 定义的手机号验证正则表达式
     */
    private Pattern pattern = Pattern.compile("1(([38]\\d)|(5[^4&&\\d])|(4[579])|(7[0135678]))\\d{8}");

    @Override
    public void initialize(Phone constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (required) {
            if (StringUtils.isEmpty(s)) {
                return false;
            }
            return pattern.matcher(s).matches();
        }
        return true;
    }
}
